package com.finance.console.dao;

import com.finance.console.entity.Budget;
import com.finance.console.storage.BaseDAO;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class BudgetDAO extends BaseDAO {
    // BudgetDAO.java

    // 添加预算（此方法字段名已正确，无需修改）
    public int addBudget(Budget budget) {
        String sql = "INSERT INTO budget" +
                " (userId, category, amount, cycle, startDate, endDate) " +
                "VALUES (?, ?, ?, ?, ?, ?)";
        return executeUpdate(sql,
                budget.getUserId(),
                budget.getCategory(),
                budget.getAmount(),
                budget.getCycle(),
                budget.getStartDate(),
                budget.getEndDate()
        );
    }

    // 按用户+周期查询预算（修正所有字段名匹配问题）
    public List<Budget> findByUserIdAndCycle(int userId, String cycle, Date start, Date end) throws SQLException {
        String sql = "SELECT * FROM budget " +
                "WHERE userId = ? AND cycle = ? " +  // 修正：userid → userId
                "AND startDate <= ? AND endDate >= ?";
        List<Budget> budgets = new ArrayList<>();
        try {
            executeQuery(sql, userId, cycle, start, end);
            while (rs.next()) {
                Budget budget = new Budget();
                budget.setBudgetId(rs.getInt("budgetId"));  // 修正：budgetid → budgetId
                budget.setUserId(rs.getInt("userId"));      // 修正：userid → userId
                budget.setCategory(rs.getString("category"));
                budget.setAmount(rs.getBigDecimal("amount"));
                budget.setCycle(rs.getString("cycle"));
                budget.setStartDate(rs.getDate("startDate"));  // 修正：start_date → startDate
                budget.setEndDate(rs.getDate("endDate"));      // 修正：end_date → endDate
                budgets.add(budget);
            }
            return budgets;
        } finally {
            close();
        }
    }

    // 更新预算金额（修正主键字段名）
    public int updateBudgetAmount(int budgetId, BigDecimal newAmount) {
        String sql = "UPDATE budget SET amount = ? WHERE budgetId = ?";  // 修正：budget_id → budgetId
        return executeUpdate(sql, newAmount, budgetId);
    }

    // 删除预算（修正主键字段名）
    public int deleteBudget(int budgetId) {
        String sql = "DELETE FROM budget WHERE budgetId = ?";  // 修正：budget_id → budgetId
        return executeUpdate(sql, budgetId);
    }
}